package com.halachawiki.server.data;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Util {
	static Logger logger = Logger.getLogger(Util.class.getSimpleName());
	
	public static String serialize(Serializable object) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			ObjectOutputStream x = new ObjectOutputStream(bos);
			x.writeObject(object);
		} catch (IOException e) {
			logger.log(Level.SEVERE, "Exception caught: ", e);
			return null;
		}
		
		return Base64.encode(bos.toByteArray());
	}
	
	public static Object deserialize(String s) {
		if (s == null) { return null; }
		try {
			byte [] bytes = Base64.decode(s);
			ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
			return ois.readObject();
		} catch (Exception e) {
			logger.log(Level.SEVERE, "Exception caught: ", e);
		}
		return null;
	}
}
